<template>
    <div>
        <basic-container>
            <el-form ref="searchForm" :model="searchForm" size="mini" :inline="true">
                <el-form-item label="物品分类">
                    <el-cascader v-model="searchForm.dangerousTypeId" :options="DepartmentTreeVChildrenNullDataQB" :show-all-levels="false"></el-cascader>
                </el-form-item>
                <el-form-item label="物品编号">
                    <el-input v-model="searchForm.coded" placeholder="请输入审批编号"></el-input>
                </el-form-item>
                <el-form-item label="物品名称">
                    <el-input v-model="searchForm.name" placeholder="请输入物品名称"></el-input>
                </el-form-item>
                <el-form-item label="物品条码">
                    <el-input v-model="searchForm.barcode" placeholder="请输入物品条码"></el-input>
                </el-form-item>
                <el-form-item label="">
                    <el-button type="primary" size="small"  plain @click.stop="searchFormSubmit()">搜索</el-button>
                    <el-button size="small"  plain @click.stop="searchFormReset()">重置</el-button>
                </el-form-item>
            </el-form>
            <avue-crud :option="tabOption" :data="tebData" :table-loading="tebLoading" :page="tebDataPage" ref="crud" @current-change='currentChange' @size-change="sizeChange">
                <template slot-scope="scope" slot="menuLeft">
                    <el-button type="primary" size="small"  plain @click.stop="addModeBtn()">添加</el-button>
                    <el-button type="primary" size="small"  plain @click.stop="typeManage()">分类管理</el-button>
                </template>
                <template slot-scope="scope" slot="menu">
                    <el-button type="primary" size="small"  plain @click.stop="updMenuBtn(scope.row,scope.index)">修改</el-button>
                    <el-button type="primary" size="small"  plain @click.stop="delMenuBtn(scope.row,scope.index)">删除</el-button>
                </template>
            </avue-crud>

        <!--分类管理-->
        <el-dialog :visible.sync="typeMode" width="40%" title="耗材分类">
            <div>
                <el-tree :data="treeData" :props="treeOption" :expand-on-click-node="false" default-expand-all>
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                        <span>
                            <el-button type="text" size="mini" @click="() => addTree(node,data)">添加</el-button>
                            <el-button type="text" size="mini" @click="() => editTree(node,data)">修改</el-button>
                            <el-button type="text" size="mini" @click="() => removeTree(node, data)">删除</el-button>
                        </span>
                    </span>
                </el-tree>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align:center">
                <el-button size="small" type="primary"  @click="addTreeNoP()">添加</el-button>
                <el-button size="small" @click="typeMode = false">关 闭</el-button>
            </div>
        </el-dialog>

        <!-- 添加分类 -->
        <el-dialog :visible.sync="dialogFormTypeVisible" width="40%" title="添加分类">
            <el-form ref="dialogFormType" :model="dialogFormType" :rules="rulesType"   label-position="left" label-width="110px">
                <el-form-item label="耗材分类：" >
                    <el-input v-model="dialogFormType.parentId" :disabled="true" v-show="false"></el-input>
                    <el-input v-model="dialogFormType.parentIdname" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="" prop='content'  label-width="110px">
                    <el-input v-model="dialogFormType.content" type="textarea" :autosize='{ minRows: 6, maxRows: 10}' placeholder="在每个分类后面敲击 “ 回车键 ” “换行”，可批量添加分类。"  @keyup.enter.native="changeInput"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
            <el-button size="small" type="primary" @click="handleAddType('dialogFormType')">添加</el-button>
            <el-button size="small"  @click="dialogFormTypeVisible = false">关 闭</el-button>
          </span>
        </el-dialog>
        <!-- 修改样品分类名字 -->
        <el-dialog title="修改分类" :visible.sync="dialogTypeTitleVisible" width="40%">
            <el-form ref="dialogTypeTitle"  :model="dialogTypeTitle" :rules="rulesTypeTitle"   label-position="left" label-width="100px">
                <el-form-item label="样品分类:" >
                    <el-input v-model="dialogTypeTitle.parentId" :disabled="true" v-show="false"></el-input>
                    <el-input v-model="dialogTypeTitle.parentIdname" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="分类选择:" >
                    <el-tree :data="treeData" :props="treeOption" :expand-on-click-node="false" default-expand-all @node-click="handleNodeClick2"></el-tree>
                </el-form-item>
                <el-form-item label="类型名称:" prop='name' >
                    <el-input v-model="dialogTypeTitle.name" placeholder="" ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align:center">
                <el-button @click="dialogTypeTitleVisible = false">关 闭</el-button>
                <el-button type="primary" @click="handleEditTypeTitle('dialogTypeTitle')">确 认</el-button>
            </div>
        </el-dialog>

        <!--耗材管理-->
        <el-dialog :visible.sync="addMode" width="30%" title="耗材管理">
            <el-form ref="addModeForm" :model="addModeForm" label-width="90px" :rules="rulesAddForm">
                <el-form-item label="物品分类:" prop='dangerousTypeId'>
                    <el-cascader  v-model="addModeForm.dangerousTypeId"  :props="props" :options="DepartmentTreeVChildrenNullData"  @change="handleChange"  ></el-cascader>
                </el-form-item>
                <el-form-item label="物品编码:" prop='coded'>
                    <el-input v-model="addModeForm.coded" placeholder="请输入物品编码"></el-input>
                </el-form-item>
                <el-form-item label="条形码号:" prop='barcode'>
                    <el-input v-model="addModeForm.barcode" placeholder="请输入条形码号"></el-input>
                </el-form-item>
                <el-form-item label="物品名称:" prop='name'>
                    <el-input v-model="addModeForm.name" placeholder="请输入物品名称"></el-input>
                </el-form-item>
                <el-form-item label="规格:" prop='specs'>
                    <el-input v-model="addModeForm.specs" placeholder="请输入规格"></el-input>
                </el-form-item>
                <el-form-item label="单位:" prop='unit'>
                    <el-input v-model="addModeForm.unit" placeholder="请输入单位"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer" style="text-align:center">
                <el-button @click="addMode = false">关 闭</el-button>
                <el-button type="primary" @click="addModeSubmit('addModeForm')">确 认</el-button>
            </div>
        </el-dialog>

        </basic-container>
    </div>
</template>

<script>
    import { tabOption } from "@/const-personal/dangerous/consumablesWarehousing/consumables.js"
    import { getListWarehouseAll, addWarehouse, updWarehouse , delWarehouse } from "@/api/public/warehouse.js"
    import { getListDangerousTypeAll, addDangerousType, updDangerousType , delDangerousType } from "@/api/consumables/receive/dangerousType.js"
    import { getListTypeInfo, addTypeInfo, updTypeInfo , delTypeInfo ,getTypeInfo} from "@/api/consumables/receive/goodsTypeInfo.js"
    import { validatenull } from '@/util/validate'
    import { DepartmentTreeV ,getDepartmentTreeOfId,DepartmentTree,DepartmentTreeVChildrenNull,getDepartmentTreeOfValue} from "@/util/util.js"
    export default {
        data(){
            return {
                //配置物品分类
                props:{
                    value:'id',
                    label:'name',
                    children:'children'
                },
                //表格结构
                tabOption:tabOption,
                //表格数据
                tebData: [],
                //表格等待
                tebLoading:false,
                //表格分页
                tebDataPage: {
                    total: 0, //总页数
                    currentPage: 1, //当前页数
                    pageSize: 10 , //每页显示多少条
                    pageSizes: [10] //显示多少条数据
                },
                DepartmentTreeVChildrenNullDataQB:[{value:'-1',label:'全部'}],
                //搜索表单数据
                searchForm: {
                    dangerousTypeId : ['-1'],
                    coded:null,
                    barcode:null,
                    name:null,
                    specs:null,
                    unit:null,

                },
                stateModeForm: {

                },
                treeOption:{
                    children: 'children',
                    label: 'name'
                },
                //模态框
                typeMode:false,
                typeModeAdd:false,
                addMode:false,
                addModeForm:{
                    dangerousTypeId: [],
                    coded:null,
                    barcode:null,
                    name:null,
                    specs:null,
                    unit:null,
                    id:null
                },
                treeDataDT:[],
                DepartmentTreeVChildrenNullData:[],
                treeData:[],
                treeDataD:[],
                dialogTypeTitleVisible:false,
                dialogTypeTitle:{name:'',parentId:0},
                dialogFormType:{
                    parentId: null,
                    name: null
                },
                dialogFormTypeVisible: false,
                rulesType:{
                    parentId:[{required: true,message: '请选择项目分类',trigger: 'change'}],
                    content:[{required: true,message: '请输入分类',trigger: 'blur'}],
                },
                rulesTypeTitle:{
                    name:[{required: true,message: "请输入分类",trigger: 'blur'}],
                    parentId:[{required: true,message: "请选择项目分类",trigger: 'change'}]
                },
                rulesAddForm:{
                    dangerousTypeId:[{required: true,message: "物品分类不能为空",trigger: 'change'}],
                    coded:[{required: true,message: "物品编码不能为空",trigger: 'change'}],
                    barcode:[{required: true,message: "条形码号不能为空",trigger: 'change'}],
                    name:[{required: true,message: "物品名称不能为空",trigger: 'change'}],
                    specs:[{required: true,message: "规格不能为空",trigger: 'change'}],
                    unit:[{required: true,message: "单位不能为空",trigger: 'change'}],
                },
            }
        },
        created(){
            this.getDangerousTypeData()
            this.searchFormSubmit()
        },
        methods :{
            currentChange(page){
                this.tebDataPage.currentPage = page;
                this.searchFormSubmit();
            },
            sizeChange(val){
                this.tebDataPage.pageSize = val;
                this.searchFormSubmit();
            },
            addModeSubmit(formName){
                let that = this;
                that.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log( that.addModeForm.dangerousTypeId)
                        // that.addModeForm.dangerousTypeId = that.addModeForm.dangerousTypeId[that.addModeForm.dangerousTypeId.length-1]
                        let dangerousTypeId  = that.addModeForm.dangerousTypeId[that.addModeForm.dangerousTypeId.length-1]
                        // that.addModeForm.dangerousTypeId =  that.addModeForm.dangerousTypeId.join(",");
                        let data = {
                            dangerousTypeId: dangerousTypeId,
                            coded: that.addModeForm.coded,
                            barcode: that.addModeForm.barcode,
                            name: that.addModeForm.name,
                            specs: that.addModeForm.specs,
                            unit: that.addModeForm.unit,
                            id: that.addModeForm.id,
                            consumablesType:that.addModeForm.dangerousTypeId.join(",")
                        } 
                        if(validatenull(that.addModeForm.id)){
                            addTypeInfo(data).then(res => {
                                if(res.data.code==200){
                                    that.$notify({ title: '操作成功', type: 'success', message: '已添加成功!'});
                                    that.searchFormSubmit()
                                    that.addMode = false;
                                } else {
                                    that.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                                }
                            })
                        } else {
                            updTypeInfo(data).then(res => {
                                if(res.data.code==200){
                                    that.$notify({ title: '操作成功', type: 'success', message: '已修改成功!'});
                                    that.searchFormSubmit()
                                    that.addMode = false;
                                } else {
                                    that.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                                }
                            })
                        }
                    }
                })
            },
            handleChange(val){ 
                //切换物品分类   赋值
                this.addModeForm.dangerousTypeId = [];//初始化数据
                this.addModeForm.dangerousTypeId = val;
                    console.log("123",val)
                },
            addModeBtn(){
                this.addMode = true
                this.addModeForm = {
                    dangerousTypeId: [],
                    coded: '',
                    barcode: '',
                    name: '',
                    specs: '',
                    unit: '',
                    id: null
                }
                console.log(this.addModeForm)
                // this.$nextTick(()=>{
                //     this.$refs['addModeForm'].resetFields();
                // })
            },
            //切割数组
            splitArr(str){
                if(!str){return}
                let arrObj = str.split(",");
                let arr = [];
                //循环转换number
                for(let i in arrObj){
                    arr.push(Number(arrObj[i]))
                }
                return arr
            },
            //修改
            updMenuBtn(row,index){
                let that = this;
                    getTypeInfo(row.id).then(res =>{
                        if(res.data.code==200){
                            that.addModeForm = {
                                // dangerousTypeId:getDepartmentTreeOfValue(that.DepartmentTreeVChildrenNullData,res.data.data.dangerousTypeId).reverse(),
                                dangerousTypeId:that.splitArr(res.data.data.consumablesType),
                                coded: res.data.data.coded,
                                barcode: res.data.data.barcode,
                                name: res.data.data.name,
                                specs: res.data.data.specs,
                                unit: res.data.data.unit,
                                id: res.data.data.id,
                            }
                            console.log(that.addModeForm.dangerousTypeId)
                            that.addMode = true
                        } else {
                            that.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                        }
                    })
            },
            handleNodeClick2(data){
                this.dialogTypeTitle.parentId=data.id;
                this.dialogTypeTitle.parentIdname=data.name;
            },
            typeManage(){
                this.typeMode = true
            },
            getDangerousTypeData(){
                let that = this;
                getListDangerousTypeAll().then(res => {
                    if(res.data.code==200){
                        that.treeData = res.data.data
                        that.treeDataD = DepartmentTreeV(that.treeData)
                        // that.DepartmentTreeVChildrenNullData = DepartmentTreeVChildrenNull(that.treeData)
                        that.DepartmentTreeVChildrenNullData = res.data.data
                        that.DepartmentTreeVChildrenNullDataQB = DepartmentTreeVChildrenNull(that.treeData,[{value:'-1',label:'全部'}])
                    }
                })
            },
            //提交搜索
            searchFormSubmit(){
                let data = { dangerousTypeId: this.searchForm.dangerousTypeId[this.searchForm.dangerousTypeId.length-1] == '-1' ? null:this.searchForm.dangerousTypeId[this.searchForm.dangerousTypeId.length-1],
                    coded:this.searchForm.coded,
                    barcode:this.searchForm.barcode,
                    name:this.searchForm.name,
                    page : this.tebDataPage.currentPage,
                    size : this.tebDataPage.pageSize}
                getListTypeInfo(data).then(res =>{
                    if(res.data.code==200){
                        this.tebData = res.data.data.list;
                        this.tebDataPage.total = res.data.data.total;
                        this.tebDataPage.currentPage = res.data.data.pageNum;
                        this.tebDataPage.pageSize = res.data.data.pageSize;
                    } else {
                        this.$notify.error({ title: '查询失败', message: '获取耗材列表失败！', type: 'danger', });
                    }
                })
            },
            //清空搜索
            searchFormReset(){
                this.searchForm ={
                    dangerousTypeId : ['-1'],
                    coded:null,
                    barcode:null,
                    name:null,
                    specs:null,
                    unit:null,
                }
            },
            //删除
            delMenuBtn(row,index){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //请求-删除
                    delTypeInfo(row.id).then(res => {
                        if(res.data.code==200){
                            this.$notify({ title: '操作成功', type: 'success', message: '已成功删除（'+row.name+'）!'});
                            this.searchFormSubmit()
                        } else {
                            this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                        }
                    })
                }).catch(() => {
                    this.$notify({ title: '已取消删除', type: 'info', });
                });
            },
            // 添加分类标题
            addTree(node, data){
                this.dialogFormType.parentId = validatenull(data.id)? null : data.id ;
                this.dialogFormType.parentIdname = validatenull(node.label)? null : node.label ;
                this.dialogFormTypeVisible = true;
            },
            addTreeNoP(node, data){
                this.dialogFormType.parentId = null;
                this.dialogFormType.parentIdname = null ;
                this.dialogFormTypeVisible = true;
            },
            // 修改分类标题
            editTree(node, data){
                let parent =  getDepartmentTreeOfId(this.treeData,data.parentId)
                this.dialogTypeTitle.parentId = data.parentId;
                this.dialogTypeTitle.parentIdname = validatenull(parent)? null: parent.name;
                this.dialogTypeTitle.name = data.name;
                this.dialogTypeTitle.id = data.id;
                this.dialogTypeTitleVisible = true;
            }, // 删除分类
            removeTree(node, data){
                this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    delDangerousType(data.id).then(res => {
                        if(res.data.code==200){
                            this.$notify({ title: '操作成功', type: 'success', message: '已成功删除!'});
                            this.getDangerousTypeData()
                        } else {
                            this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                        }
                    })
                }).catch(() => {
                    console.log("已取消删除");
                });

            },
            // 确认新增-分类--树
            handleAddType(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let valuedata = this.dialogFormType.content.split(/\s+|&nbsp;/ig)
                        let contentData = []
                        valuedata.forEach(item=>{
                            if (!validatenull(item)){
                                contentData.push(item)
                            }
                        })
                        let data = []
                        contentData.forEach(item=>{
                            if (!validatenull(item)){
                                data.push({name:item,
                                    parentId:this.dialogFormType.parentId,
                                    isDelete:0})
                            }
                        })
                        addDangerousType(data).then(res => {
                            if(res.data.code==200){
                                this.$notify({ title: '操作成功', type: 'success', message: '已添加成功!'});
                                this.dialogFormTypeVisible = false;
                                this.$refs[formName].resetFields();
                                this.getDangerousTypeData()
                            } else {
                                this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                            }
                        })
                    }
                })
            },
            // 确认修改树
            handleEditTypeTitle(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        updDangerousType({
                            parentId : this.dialogTypeTitle.parentId,
                            name : this.dialogTypeTitle.name,
                            id : this.dialogTypeTitle.id,
                        }).then(res => {
                            if(res.data.code==200){
                                this.$notify({ title: '操作成功', type: 'success', message: '已修改成功!'});
                                this.dialogTypeTitleVisible=false;
                                this.$refs[formName].resetFields();
                                this.getDangerousTypeData()
                            } else {
                                this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                            }
                        })
                    }
                })
            },
        }
    }
</script>

<style scoped>

    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>